# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.views.decorators.http import require_http_methods

from common.channel.channel_map import CHANNEL_HANDLER
from common.channel.model import CHANNEL_TYPE
from common.utils import exceptions as err
from common.utils import track_logging

_LOGGER = track_logging.getLogger(__name__)


@require_http_methods(['GET', 'POST'])
def notify_all(request, channel_name, app_id):
    try:
        if channel_name.find('_') != -1:
            channel_name = channel_name.replace('_', '')
        chn_type = CHANNEL_TYPE.get_value(channel_name.upper())
        _LOGGER.info('>>>>>>>>>>>>>>>>>>>>>>>channel_name:%s, chn_type:%s' % (channel_name, chn_type))
        chn_handler = CHANNEL_HANDLER[chn_type]
        return_code = chn_handler.check_notify_sign(request, app_id)
        return HttpResponse(return_code, status=200)
    except err.SignError as e:
        _LOGGER.warn('%s notify sign error, %s', channel_name, e)
        return HttpResponse('sign error', status=200)
    except err.IpWhiteListsError as e:
        _LOGGER.warn('%s notify ip error, %s', channel_name, e)
        return HttpResponse('ip not in white lists', status=200)
    except err.NotResponsePayIdError as e:
        _LOGGER.warn('%s notify response is not pay_id, %s', channel_name, e)
        return HttpResponse('response is not pay_id', status=200)
    except err.NotPayOrderError as e:
        _LOGGER.warn('%s notify list not pay_order, %s', channel_name, e)
        return HttpResponse('this order is not found', status=200)
    except err.ProcessedPayOrderError as e:
        _LOGGER.warn('%s notify this order is processed, %s', channel_name, e)
        return HttpResponse('this order is processed and not pay success', status=200)
    except err.MoneyNotMatchError as e:
        _LOGGER.warn('%s notify pay money not match, %s', channel_name, e)
        return HttpResponse('pay money not match', status=200)
    except err.NotChannelError as e:
        _LOGGER.warn('%s notify not match channel, %s', channel_name, e)
        return HttpResponse('not channel', status=200)
    except err.AppIdNotMatchError as e:
        _LOGGER.warn('%s notify appid not match channel appid, %s', channel_name, e)
        return HttpResponse('channel appid not match', status=200)
    except err.MoneyMoreMaxError as e:
        _LOGGER.warn('%s notify pay money more than max_amount, %s', channel_name, e)
        return HttpResponse('pay money more than max_amount', status=200)
    except Exception as e:
        _LOGGER.exception('%s notify exception.(%s)', channel_name, e)
        return HttpResponse('other error', status=400)
